<template>
  <div class="component-property-editor">
    <!-- 通用属性 -->
    <div class="property-section">
      <h4 class="section-title">通用属性</h4>
      
      <el-form :model="localComponent" label-width="80px" size="mini">
        <!-- 位置和尺寸 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="X坐标">
              <el-input-number
                v-model="localComponent.position.x"
                :min="0"
                :max="1000"
                controls-position="right"
                @change="handleUpdate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="Y坐标">
              <el-input-number
                v-model="localComponent.position.y"
                :min="0"
                :max="2000"
                controls-position="right"
                @change="handleUpdate"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="宽度">
              <el-input-number
                v-model="localComponent.position.width"
                :min="20"
                :max="800"
                controls-position="right"
                @change="handleUpdate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="高度">
              <el-input-number
                v-model="localComponent.position.height"
                :min="20"
                :max="600"
                controls-position="right"
                @change="handleUpdate"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 层级 -->
        <el-form-item label="层级">
          <el-input-number
            v-model="localComponent.zIndex"
            :min="1"
            :max="1000"
            controls-position="right"
            @change="handleUpdate"
          />
        </el-form-item>
      </el-form>
    </div>

      <!-- 参数绑定部分 -->
    <div v-if="supportsParamBinding" class="property-section">
      <h4 class="section-title">参数绑定</h4>
      
      <el-form :model="localComponent.content" label-width="100px" size="mini">
        <el-form-item label="绑定参数">
          <el-select
            v-model="localComponent.content.paramCode"
            placeholder="选择参数"
            filterable
            clearable
            @change="handleParamChange"
          >
            <el-option-group
              v-for="group in paramOptions"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="param in group.options"
                :key="param.value"
                :label="param.label"
                :value="param.value"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        
        <!-- 参数信息显示 -->
        <div v-if="selectedParam" class="param-info">
          <el-descriptions :column="1" size="mini" border>
            <el-descriptions-item label="参数类型">
              {{ getParamTypeText(selectedParam.paramType) }}
            </el-descriptions-item>
            <el-descriptions-item label="数据类型">
              {{ getDataTypeText(selectedParam.dataType) }}
            </el-descriptions-item>
            <el-descriptions-item v-if="selectedParam.unit" label="单位">
              {{ selectedParam.unit }}
            </el-descriptions-item>
            <el-descriptions-item v-if="selectedParam.isMultiMeasure" label="测量次数">
              {{ selectedParam.multiMeasureCount }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-form>
    </div>

        <!-- 布局表格特定属性 -->
    <div v-if="isLayoutTable" class="property-section">
      <layout-table-property-editor
        :component="localComponent"
        :config="config"
        :selected-cell-data="selectedCellData"
        @update="handleUpdate"
        @delete="handleDelete"
      />
    </div>

    <!-- 组件特定属性 -->
    <div class="property-section">
      <h4 class="section-title">内容属性</h4>
      
      <!-- 文本组件属性 -->
      <div v-if="localComponent.type === 'text'" class="type-specific-props">
        <el-form :model="localComponent.content" label-width="80px" size="mini">
          <el-form-item label="文本内容">
            <el-input
              v-model="localComponent.content.text"
              type="textarea"
              :rows="3"
              placeholder="请输入文本内容"
              @input="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="字体大小">
            <el-input-number
              v-model="localComponent.content.fontSize"
              :min="8"
              :max="72"
              controls-position="right"
              @change="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="字体粗细">
            <el-select
              v-model="localComponent.content.fontWeight"
              placeholder="请选择字体粗细"
              @change="handleUpdate"
            >
              <el-option label="正常" value="normal" />
              <el-option label="加粗" value="bold" />
              <el-option label="细体" value="lighter" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="对齐方式">
            <el-radio-group
              v-model="localComponent.content.align"
              @change="handleUpdate"
            >
              <el-radio label="left">左对齐</el-radio>
              <el-radio label="center">居中</el-radio>
              <el-radio label="right">右对齐</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="文字颜色">
            <el-color-picker
              v-model="localComponent.content.color"
              @change="handleUpdate"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格组件属性 -->
      <div v-else-if="localComponent.type === 'table'" class="type-specific-props">
        <el-form :model="localComponent.content" label-width="80px" size="mini">
          <el-form-item label="显示表头">
            <el-switch
              v-model="localComponent.content.showHeader"
              @change="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="显示边框">
            <el-switch
              v-model="localComponent.content.border"
              @change="handleUpdate"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 参数组件属性 -->
      <div v-else-if="localComponent.type === 'parameter'" class="type-specific-props">
        <el-form :model="localComponent.content" label-width="80px" size="mini">
          <el-form-item label="参数编码">
            <el-input
              v-model="localComponent.content.paramCode"
              placeholder="请输入参数编码"
              @input="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="显示名称">
            <el-input
              v-model="localComponent.content.displayName"
              placeholder="请输入显示名称"
              @input="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="显示格式">
            <el-select
              v-model="localComponent.content.format"
              placeholder="请选择显示格式"
              @change="handleUpdate"
            >
              <el-option label="仅数值" value="value" />
              <el-option label="数值+单位" value="valueWithUnit" />
              <el-option label="参数名+数值" value="nameValue" />
              <el-option label="完整显示" value="full" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="小数位数">
            <el-input-number
              v-model="localComponent.content.precision"
              :min="0"
              :max="6"
              controls-position="right"
              @change="handleUpdate"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 图片组件属性 -->
      <div v-else-if="localComponent.type === 'image'" class="type-specific-props">
        <el-form :model="localComponent.content" label-width="80px" size="mini">
          <el-form-item label="图片URL">
            <el-input
              v-model="localComponent.content.imageUrl"
              placeholder="请输入图片URL或上传图片"
              @input="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="替代文本">
            <el-input
              v-model="localComponent.content.alt"
              placeholder="请输入图片描述"
              @input="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="对齐方式">
            <el-select
              v-model="localComponent.content.align"
              placeholder="请选择对齐方式"
              @change="handleUpdate"
            >
              <el-option label="左对齐" value="left" />
              <el-option label="居中" value="center" />
              <el-option label="右对齐" value="right" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <!-- 页眉组件属性 -->
      <div v-else-if="localComponent.type === 'header'" class="type-specific-props">
        <el-form :model="localComponent.content" label-width="80px" size="mini">
          <el-form-item label="主标题">
            <el-input
              v-model="localComponent.content.title"
              placeholder="请输入主标题"
              @input="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="副标题">
            <el-input
              v-model="localComponent.content.subtitle"
              placeholder="请输入副标题"
              @input="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="显示边框">
            <el-switch
              v-model="localComponent.content.showBorder"
              @change="handleUpdate"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 页脚组件属性 -->
      <div v-else-if="localComponent.type === 'footer'" class="type-specific-props">
        <el-form :model="localComponent.content" label-width="80px" size="mini">
          <el-form-item label="左侧文本">
            <el-input
              v-model="localComponent.content.leftText"
              placeholder="请输入左侧文本"
              @input="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="中间文本">
            <el-input
              v-model="localComponent.content.centerText"
              placeholder="请输入中间文本"
              @input="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="右侧文本">
            <el-input
              v-model="localComponent.content.rightText"
              placeholder="请输入右侧文本"
              @input="handleUpdate"
            />
          </el-form-item>
          
          <el-form-item label="显示边框">
            <el-switch
              v-model="localComponent.content.showBorder"
              @change="handleUpdate"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 未知组件类型 -->
      <div v-else class="unknown-component">
        <el-alert
          title="未知组件类型"
          type="warning"
          description="无法编辑该类型组件的属性"
          show-icon
          :closable="false"
        />
      </div>
    </div>

    <!-- 样式属性 -->
    <div class="property-section">
      <h4 class="section-title">样式属性</h4>
      
      <el-form :model="localComponent.style" label-width="80px" size="mini">
        <el-form-item label="背景颜色">
          <el-color-picker
            v-model="localComponent.style.backgroundColor"
            @change="handleUpdate"
          />
        </el-form-item>
        
        <el-form-item label="边框颜色">
          <el-color-picker
            v-model="localComponent.style.borderColor"
            @change="handleUpdate"
          />
        </el-form-item>
        
        <el-form-item label="边框宽度">
          <el-input-number
            v-model="localComponent.style.borderWidth"
            :min="0"
            :max="10"
            controls-position="right"
            @change="handleUpdate"
          />
        </el-form-item>
        
        <el-form-item label="内边距">
          <el-input-number
            v-model="localComponent.style.padding"
            :min="0"
            :max="50"
            controls-position="right"
            @change="handleUpdate"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="property-actions">
      <el-button
        type="danger"
        size="mini"
        icon="el-icon-delete"
        @click="handleDelete"
      >
        删除组件
      </el-button>
      
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-copy-document"
        @click="handleDuplicate"
      >
        复制组件
      </el-button>
    </div>
  </div>
</template>

<script>
import { deepClone,getAllParamItems  } from '@/utils/tools'
import LayoutTablePropertyEditor from './renderers/LayoutTablePropertyEditor.vue'
export default {
  name: 'ComponentPropertyEditor',
  components: {
    LayoutTablePropertyEditor
  },
  props: {
    component: {
      type: Object,
      required: true,
      default: () => ({})
    },
    config: {
      type: Object,
      default: () => ({})
    },
     selectedCellData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      localComponent: {}
    }
  },
   computed: {
    supportsParamBinding() {
      const supportedTypes = ['parameter', 'number', 'multiMeasure', 'dynamicTable']
      return supportedTypes.includes(this.localComponent.type)
    },
    isLayoutTable() {
      return this.localComponent.type === 'layoutTable'
    },
    paramOptions() {
      if (!this.config.paramGroups) return []
      
      const allParams = getAllParamItems(this.config.paramGroups)
      const groups = {}
      
      allParams.forEach(param => {
        const groupName = this.getParamGroupName(param.paramId) || '其他参数'
        
        if (!groups[groupName]) {
          groups[groupName] = []
        }
        
        groups[groupName].push({
          label: `${param.paramName} (${param.paramCode})`,
          value: param.paramCode
        })
      })
      
      return Object.keys(groups).map(label => ({
        label,
        options: groups[label]
      }))
    },
    
    selectedParam() {
      const paramCode = this.localComponent.content?.paramCode
      if (!paramCode || !this.config.paramGroups) return null
      
      const allParams = getAllParamItems(this.config.paramGroups)
      return allParams.find(param => param.paramCode === paramCode)
    }
  },
  watch: {
    component: {
      handler(newVal) {
        this.localComponent = deepClone(newVal)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
     handleParamChange(paramCode) {
      if (paramCode && this.selectedParam) {
        // 自动更新组件属性基于参数配置
        this.updateComponentFromParam(this.selectedParam)
      }
      this.handleUpdate()
    },
     updateComponentFromParam(paramConfig) {
      // 根据参数配置更新组件属性
      if (paramConfig.dataType === 'number') {
        this.localComponent.content.precision = paramConfig.precision || 2
      }
      
      if (paramConfig.isMultiMeasure) {
        this.localComponent.content.multiMeasureCount = paramConfig.multiMeasureCount
      }
      
      this.localComponent.content.displayName = paramConfig.paramName
    },

     getParamGroupName(paramId) {
      // 根据paramId查找所属参数组
      function findGroup(groups, targetParamId) {
        for (const group of groups) {
          if (group.paramItems?.some(param => param.paramId === targetParamId)) {
            return group.groupName
          }
          if (group.childGroups) {
            const found = findGroup(group.childGroups, targetParamId)
            if (found) return found
          }
        }
        return null
      }
      
      return findGroup(this.config.paramGroups || [], paramId)
    },
     getParamTypeText(paramType) {
      const typeMap = {
        base: '基础参数',
        calculation: '计算参数',
        reference: '引用参数'
      }
      return typeMap[paramType] || paramType
    },
    
    getDataTypeText(dataType) {
      const typeMap = {
        text: '文本',
        number: '数值',
        date: '日期',
        select: '选择'
      }
      return typeMap[dataType] || dataType
    },
    /**
     * 处理属性更新
     */
    handleUpdate() {
      this.$emit('update', this.localComponent)
    },

    /**
     * 删除组件
     */
    handleDelete() {
      this.$confirm('确定要删除这个组件吗？', '删除组件', {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          this.$emit('delete', this.localComponent.id)
        })
        .catch(() => {})
    },

    /**
     * 复制组件
     */
    handleDuplicate() {
      this.$emit('duplicate', this.localComponent)
    },

    /**
     * 获取组件类型名称
     */
    getComponentTypeName(type) {
      const typeMap = {
        text: '文本',
        table: '表格',
        parameter: '参数',
        image: '图片',
        header: '页眉',
        footer: '页脚',
        signature: '签名'
      }
      return typeMap[type] || type
    }
  }
}
</script>

<style scoped>
.component-property-editor {
  padding: 0;
  height: 100%;
  overflow-y: auto;
}

.property-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e8eb;
}

.property-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 15px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f2f5;
}

.type-specific-props {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #e6e8eb;
}

.unknown-component {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.property-actions {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #e6e8eb;
  display: flex;
  gap: 10px;
  justify-content: space-between;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .component-property-editor {
    padding: 10px;
  }
  
  .property-section {
    margin-bottom: 15px;
    padding-bottom: 10px;
  }
  
  .type-specific-props {
    padding: 10px;
  }
  
  .property-actions {
    flex-direction: column;
  }
}

.param-info {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}
</style>